using System;
using System.Collections;
using UnityEngine;

public static class JsonDownloader
{
	public static void StartDownload(string serverPath, string jsonKey = null, Action<string> callBack = null)
	{
		CoroutineRunner.Instance.StartCoroutine(Download(serverPath, jsonKey, callBack));
	}

	private static IEnumerator Download(string serverPath, string jsonKey = null, Action<string> callBack = null)
	{
		WWW downloadData = new WWW(serverPath);
		while (!downloadData.isDone)
		{
			yield return null;
		}
		string text = string.Empty;
		if (!string.IsNullOrEmpty(downloadData.error))
		{
			BCWDebug.LogError("Download data error from: " + serverPath + " Error: " + downloadData.error);
			if (!string.IsNullOrEmpty(jsonKey))
			{
				text = BCWStorage.Get<string>(jsonKey);
			}
		}
		else
		{
			if (!string.IsNullOrEmpty(jsonKey))
			{
				BCWStorage.Set(jsonKey, downloadData.text);
			}
			text = downloadData.text;
		}
		if (callBack != null)
		{
			callBack(text);
		}
	}
}
